<?php
namespace control;

/*
*往来单位一览表类
*/

use JetBrains\PhpStorm\NoReturn;

class currentUnitMxClass extends adIndexClass
{
    private const page = 'currentUnitMx';
    private const title = '往来单位一览表';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'supplierSearch':
                $tr = [
                    'category'          => [
                        'name'  => "供应商类别",
                        'width' => 200,
                    ],
                    'code'  => [
                        'name'  => '供应商编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'         => [
                        'name'  => '供应商',
                        'width' => 200,
                    ],
                    'initMoney'          => [
                        'name'  => '期初余额('.static::$unit.')',
                        'width' => 200,
                    ],
                    'purchaseMoney'          => [
                        'name'  => '采购金额('.static::$unit.')',
                        'width' => 200,
                    ],
                    'otherPay'          => [
                        'name'  => '其他应付金额('.static::$unit.')',
                        'width' => 200,
                    ],
                    'payMoney'          => [
                        'name'  => '实际付款金额('.static::$unit.')',
                        'width' => 150,
                    ],
                    'payable'          => [
                        'name'  => '应付款金额('.static::$unit.')',
                        'width' => 150,
                    ]
                ];
                break;
            default:
                $tr = [
                    'classify'          => [
                        'name'  => "客户类别",
                        'width' => 200,
                    ],
                    'orderNo'  => [
                        'name'  => '客户编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'companyName'         => [
                        'name'  => '客户',
                        'width' => 200,
                    ],
                    'initMoney'          => [
                        'name'  => '期初余额('.static::$unit.')',
                        'width' => 200,
                    ],
                    'saleMoney'          => [
                        'name'  => '销售金额('.static::$unit.')',
                        'width' => 200,
                    ],
                    'otherIn'          => [
                        'name'  => '其他应收金额('.static::$unit.')',
                        'width' => 200,
                    ],
                    'recMoney'          => [
                        'name'  => '实际收款金额('.static::$unit.')',
                        'width' => 150,
                    ],
                    'receivables'          => [
                        'name'  => '应收款金额('.static::$unit.')',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "客户名称" => text(array("name" => "name")),
                    "客户类别"   => select(array('name' => 'type', 'option' => explode('，', para('clientType')))),
                    '单据日期' => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function homeSearch()
    {
        $like = [
            "companyName"         => $this->post('name'),
            "classify"         => $this->post('type'),
        ];
        //全等查询数组
        $equal = array(
            'isDeal'=>1,
        );
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'orderNo',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(["like" => $like, "=" => $equal])." and coid = '".self::$coid."'";
        $page = $this->page([
            "table" => "kehu",
            "where" =>$where,
            "order" => $orderBy['orderBy']
        ]);
        $saleWhere = " and main.coid = '".self::$coid."'";//销售金额条件
        $recWhere = '';//实际收款金额条件
        if ($this->post('time')){
            $timeArr = explode(' ~ ', $this->post('time'));
            $recordWhere=" and targetDate < '{$timeArr[0]}'";
            $saleWhere.=" and main.recordDate >= '{$timeArr[0]}' and main.recordDate <= '{$timeArr[1]}'";
            $recWhere.=" and targetDate >= '{$timeArr[0]}' and targetDate <= '{$timeArr[1]}'";
        }else{
            $recordWhere=" and classify = '客户期初'";
        }
        $_SESSION[self::page]['clientTime'] = $this->post('time');
        $_SESSION[self::page]['client'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['khid']),
            );
            $liButton[] = $this->dominate($dominate);
            //期初余额
            $initMoney = find(array('table'=>'record','where'=>"typeId = '$array[khid]'".$recordWhere,'sum'=>"money"));
            //销售金额
            $saleMoney = self::sale_money('sale_send_order',$array['khid'],$saleWhere);
            $refundMoney = self::sale_money('sale_refund_order',$array['khid'],$saleWhere);
            $saleMoney = $saleMoney-$refundMoney;
            //其他应收
            $otherIn = find(['table'=>'record','where'=>"coid = '".self::$coid."' and typeId = '$array[khid]' and classify = '其他应收'",'sum'=>"money"]);
            //其他应付
            $otherPay = find(['table'=>'record','where'=>"coid = '".self::$coid."' and typeId = '$array[khid]' and classify = '其他应付'",'sum'=>"money"]);
            //实际收款金额
            $recMoney = find(array('table'=>'record','where'=>"typeId = '$array[khid]' and direction = '-'".$recWhere,'sum'=>"money"));
            $recMoney = $recMoney!=0?-$recMoney:0;
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'initMoney':
                        $row[] = $initMoney;
                        break;
                    case 'saleMoney':
                        $row[] = round($saleMoney,2);
                        break;
                    case 'otherIn':
                        $row[] = round($otherIn,2);
                        break;
                    case 'recMoney':
                        $row[] = round($recMoney,2);
                        break;
                    case 'receivables':
                        $row[] = round($otherIn+$saleMoney-$otherPay-$recMoney+$initMoney,2);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //期初余额
        $initMoney = find(array('table'=>'record','where'=>"typeId in (select khid from kehu where 1=1 {$where})".$recordWhere,'sum'=>"money"));
        //销售金额
        //销售金额
        $saleMoney = find(array('table' => 'sale_send_order_detail as a join sale_send_order as main on a.orderId = main.id join inventory_detail as b on a.id = b.sourceId join record as re on b.id = re.sourceId', "single" => "main.state = '已确认' and main.khid in (select khid from kehu where 1=1 {$where})".$saleWhere, 'field' => "ifnull(sum(re.money),0) as total"))['total']??0;
        //退货金额
        $saleMoney += find(array('table' => 'sale_refund_order_detail as a join sale_refund_order as main on a.orderId = main.id join inventory_detail as b on a.id = b.sourceId join record as re on b.id = re.sourceId', "single" => "main.state ='已确认' and main.khid in (select khid from kehu where 1=1 {$where})".$saleWhere, 'field' => "ifnull(sum(re.money),0) as total"))['total']??0;
        //其他应收
        $otherIn = find(['table'=>'record','where'=>"coid = '".self::$coid."' and typeId in (select khid from kehu where 1=1 {$where}) and classify = '其他应收'",'sum'=>"money"]);
        //其他应付
        $otherPay = find(['table'=>'record','where'=>"coid = '".self::$coid."' and typeId in (select khid from kehu where 1=1 {$where}) and classify = '其他应付'",'sum'=>"money"]);
        //实际收款金额
        $recMoney = find(array('table'=>'record','where'=>"typeId in (select khid from kehu where 1=1 {$where}) and direction = '-'".$recWhere,'sum'=>"money"));
        $recMoney = $recMoney!=0?-$recMoney:0;
        $total    = [
            'initMoney'        => self::formattingFigure($initMoney),
            'saleMoney'   => self::formattingFigure($saleMoney),
            'otherIn'   => self::formattingFigure($otherIn),
            'recMoney'   => self::formattingFigure($recMoney),
            'receivables'   => self::formattingFigure($otherIn+$saleMoney-$otherPay-$recMoney+$initMoney),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function supplierOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "供应商名称" => text(array("name" => "name")),
                    "供应商类别"   => select(array('name' => 'type', 'option' => explode('，', para('supplierCategory')))),
                    '单据日期' => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 供应商
     *
     */
    public function supplier(): bool|string
    {
        $html = $this->supplierOptions(false);
        //控件
        $button = "";
        if ($this->power('currentUnitMxSupplier', "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."',exportFun:'exportDataSupplier',classify:'供应商一览表',checkbox:'supplierId'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }
    public function supplierSearch()
    {
        $like = [
            "name"         => $this->post('name'),
            "category"         => $this->post('type'),
        ];
        //全等查询数组
        $equal = array(
            "coid" => self::$coid,
        );
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'code',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(["like" => $like, "=" => $equal]);
        $page = $this->page([
            "table" => "supplier",
            "where" =>$where,
            "order" => $orderBy['orderBy']
        ]);
        $saleWhere = " and main.coid = '".self::$coid."'";//销售金额条件
        $settleWhere = '';
        $recWhere = '';//实际收款金额条件
        if ($this->post('time')){
            $timeArr = explode(' ~ ', $this->post('time'));
            $recordWhere=" and targetDate < '{$timeArr[0]}'";
            $saleWhere.=" and main.recordDate >= '{$timeArr[0]}' and main.recordDate <= '{$timeArr[1]}'";
            $recWhere.=" and targetDate >= '{$timeArr[0]}' and targetDate <= '{$timeArr[1]}'";
            $settleWhere.=" and recordDate >= '{$timeArr[0]}' and recordDate <= '{$timeArr[1]}'";
        }else{
            $recordWhere=" and classify = '供应商期初'";
        }
        $_SESSION[self::page]['supplierTime'] = $this->post('time');
        $_SESSION[self::page]['supplier'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("supplierForm", "supplierId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "supplierId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //期初余额
            $initMoney = find(array('table'=>'record','where'=>"typeId = '$array[id]'".$recordWhere,'sum'=>"money"));
            $initMoney = $initMoney!=0?-$initMoney:$initMoney;
            //其他应付
            $otherPay = find(['table'=>'record','where'=>"coid = '".self::$coid."' and typeId = '$array[id]' and classify = '其他应付'",'sum'=>"money"]);
            //其他应收
            $otherIn = find(['table'=>'record','where'=>"coid = '".self::$coid."' and typeId = '$array[id]' and classify = '其他应收'",'sum'=>"money"]);
            //采购金额
            $purchaseMoney = self::sale_money('purchase_get_order',$array['id'],$saleWhere);
            //委外结算金额
            $purchaseMoney += self::sale_money('outsource_settle',$array['id'],$settleWhere);
            $refundMoney = self::sale_money('purchase_refund_order',$array['id'],$saleWhere);
            $purchaseMoney =$purchaseMoney- $refundMoney;
            //实际付款金额
            $payMoney = find(array('table'=>'record','where'=>"typeId = '$array[id]' and direction = '+'".$recWhere,'sum'=>"money"));
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'initMoney':
                        $row[] = $initMoney;
                        break;
                    case 'purchaseMoney':
                        $row[] = round($purchaseMoney,2);
                        break;
                    case 'otherPay':
                        $row[] = round($otherPay,2);
                        break;
                    case 'payMoney':
                        $row[] = round($payMoney,2);
                        break;
                    case 'payable':
                        $row[] = round($otherPay+$purchaseMoney-$otherIn-$payMoney+$initMoney,2);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //期初余额
        $initMoney = find(array('table'=>'record','where'=>"typeId in (select id from supplier where 1=1 {$where})".$recordWhere,'sum'=>"money"));
        $initMoney = $initMoney!=0?-$initMoney:$initMoney;
        //其他应付
        $otherPay = find(['table'=>'record','where'=>"coid = '".self::$coid."' and typeId in (select id from supplier where 1=1 {$where}) and classify = '其他应付'",'sum'=>"money"]);
        //其他应收
        $otherIn = find(['table'=>'record','where'=>"coid = '".self::$coid."' and typeId in (select id from supplier where 1=1 {$where}) and classify = '其他应收'",'sum'=>"money"]);
        //采购金额
        //采购金额
        $purchaseMoney = -find(array('table' => 'purchase_get_order_detail as a join purchase_get_order as main on a.orderId = main.id join inventory_detail as b on a.id = b.sourceId join record as re on b.id = re.sourceId', "single" => "main.state ='已确认' and main.supplierId in (select id from supplier where 1=1 {$where})".$saleWhere, 'field' => "ifnull(sum(re.money),0) as total"))['total']??0;
        //委外结算金额
        $purchaseMoney += find(array('table' => 'outsource_settle', "single" => "state ='已确认' and supplierId in (select id from supplier where 1=1 {$where})".$settleWhere, 'sum' => "money"));


        $purchaseMoney -= find(array('table' => 'purchase_refund_order_detail as a join purchase_refund_order as main on a.orderId = main.id join inventory_detail as b on a.id = b.sourceId join record as re on b.id = re.sourceId', "single" => "main.state ='已确认' and main.supplierId in (select id from supplier where 1=1 {$where})".$saleWhere, 'field' => "ifnull(sum(re.money),0) as total"))['total']??0;
        //实际付款金额
        $payMoney = find(array('table'=>'record','where'=>"typeId in (select id from supplier where 1=1 {$where}) and direction = '+'".$recWhere,'sum'=>"money"));
        $total    = [
            'initMoney'        => self::formattingFigure($initMoney),
            'purchaseMoney'   => self::formattingFigure($purchaseMoney),
            'otherPay'   => self::formattingFigure($otherPay),
            'payMoney'   => self::formattingFigure($payMoney),
            'payable'   => self::formattingFigure($otherPay+$purchaseMoney-$otherIn-$payMoney+$initMoney),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='supplierForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 销售或采购单据金额
     */
    private static function sale_money($tableName,$targetId,$where){
        $totalMoney = 0;
        if ($tableName == 'sale_send_order') {
            //单据金额
            $totalMoney = find(array('table' => 'sale_send_order_detail as a join sale_send_order as main on a.orderId = main.id join inventory_detail as b on a.id = b.sourceId join record as re on b.id = re.sourceId', "single" => "main.state = '已确认' and main.khid = '$targetId'".$where, 'field' => "ifnull(sum(re.money),0) as total"))['total']??0;//
        } elseif($tableName =='sale_refund_order') {
            //单据金额
            $totalMoney = find(array('table' => 'sale_refund_order_detail as a join sale_refund_order as main on a.orderId = main.id join inventory_detail as b on a.id = b.sourceId join record as re on b.id = re.sourceId', "single" => "main.state ='已确认' and main.khid = '$targetId'".$where, 'field' => "ifnull(sum(re.money),0) as total"))['total']??0;
            $totalMoney = -$totalMoney;
        }elseif ($tableName == 'purchase_get_order') {
            //单据金额
            $totalMoney = find(array('table' => 'purchase_get_order_detail as a join purchase_get_order as main on a.orderId = main.id join inventory_detail as b on a.id = b.sourceId join record as re on b.id = re.sourceId', "single" => "main.state ='已确认' and main.supplierId = '$targetId'".$where, 'field' => "ifnull(sum(re.money),0) as total"))['total']??0;
            $totalMoney = -$totalMoney;
        } elseif ($tableName == 'purchase_refund_order')  {
            //单据金额
            $totalMoney = find(array('table' => 'purchase_refund_order_detail as a join purchase_refund_order as main on a.orderId = main.id join inventory_detail as b on a.id = b.sourceId join record as re on b.id = re.sourceId', "single" => "main.state ='已确认' and main.supplierId = '$targetId'".$where, 'field' => "ifnull(sum(re.money),0) as total"))['total']??0;
        }elseif($tableName =='outsource_settle'){
            $totalMoney = find(array('table' => 'outsource_settle', "single" => "state ='已确认' and supplierId = '$targetId'".$where, 'sum' => "money"));
        }
        return $totalMoney;
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = "您还没有导出的权限";
        }  else {
            $clientTime= $_SESSION[self::page]['clientTime'];
            $saleWhere = " and main.coid = '".self::$coid."'";//销售金额条件
            $recWhere = '';//实际收款金额条件
            if ($clientTime){
                $timeArr = explode(' ~ ', $clientTime);
                $recordWhere=" and targetDate < '{$timeArr[0]}'";
                $saleWhere.=" and main.recordDate >= '{$timeArr[0]}' and main.recordDate <= '{$timeArr[1]}'";
                $recWhere.=" and targetDate >= '{$timeArr[0]}' and targetDate <= '{$timeArr[1]}'";
            }else{
                $recordWhere =" and classify = '客户期初'";
            }
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => "kehu",
                    "where" => "khid in ('".implode("','", $checkedId)."') order by orderNo asc",
                ))['array'];
            }else{
                $sql = $_SESSION[self::page]['client'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                //期初余额
                $initMoney = find(array('table'=>'record','where'=>"typeId = '$array[khid]'".$recordWhere,'sum'=>"money"));
                //销售金额
                $saleMoney = self::sale_money('sale_send_order',$array['khid'],$saleWhere);
                $refundMoney = self::sale_money('sale_refund_order',$array['khid'],$saleWhere);
                $saleMoney = $saleMoney-$refundMoney;
                //其他应收
                $otherIn = find(['table'=>'record','where'=>"coid = '".self::$coid."' and typeId = '$array[khid]' and classify = '其他应收'",'sum'=>"money"]);
                //其他应付
                $otherPay = find(['table'=>'record','where'=>"coid = '".self::$coid."' and typeId = '$array[khid]' and classify = '其他应付'",'sum'=>"money"]);
                //实际收款金额
                $recMoney = find(array('table'=>'record','where'=>"typeId = '$array[khid]' and direction = '-'".$recWhere,'sum'=>"money"));
                $recMoney = $recMoney!=0?-$recMoney:0;
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '客户类别'=>$array['classify'],
                            '客户编码'=>$array['orderNo'],
                            '客户'=>$array['companyName'],
                            '期初余额'=>$initMoney,
                            '销售金额'=>round($saleMoney,2),
                            '其他应收金额'=>round($otherIn,2),
                            '实际收款金额'=>round($recMoney,2),
                            '应收款金额'=>round($otherIn+$saleMoney-$otherPay-$recMoney+$initMoney,2),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = $this->control['name'] . "导出了往来单位一览表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "往来单位一览表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 按供应商导出
     */
    public function exportDataSupplier()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power('currentUnitMxSupplier', 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $clientTime= $_SESSION[self::page]['supplierTime'];
            $saleWhere = '';//销售金额条件
            $recWhere = '';//实际收款金额条件
            $settleWhere = '';
            if ($clientTime){
                $timeArr = explode(' ~ ', $clientTime);
                $recordWhere=" and targetDate < '{$timeArr[0]}'";
                $saleWhere.=" and main.recordDate >= '{$timeArr[0]}' and main.recordDate <= '{$timeArr[1]}'";
                $recWhere.=" and targetDate >= '{$timeArr[0]}' and targetDate <= '{$timeArr[1]}'";
                $recWhere.=" and targetDate >= '{$timeArr[0]}' and targetDate <= '{$timeArr[1]}'";
            }else{
                $recordWhere=" and classify = '供应商期初'";
            }
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => "supplier",
                    "where" => "id in ('".implode("','", $checkedId)."') order by code asc",
                ))['array'];
            }else{
                $sql = $_SESSION[self::page]['supplier'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                //期初余额
                $initMoney = find(array('table'=>'record','where'=>"typeId = '$array[id]'".$recordWhere,'sum'=>"money"));
                $initMoney = $initMoney!=0?-$initMoney:$initMoney;
                //其他应付
                $otherPay = find(['table'=>'record','where'=>"coid = '".self::$coid."' and typeId = '$array[id]' and classify = '其他应付'",'sum'=>"money"]);
                //其他应收
                $otherIn = find(['table'=>'record','where'=>"coid = '".self::$coid."' and typeId = '$array[id]' and classify = '其他应收'",'sum'=>"money"]);
                //采购金额
                $purchaseMoney = self::sale_money('purchase_get_order',$array['id'],$saleWhere);
                //委外结算金额
                $purchaseMoney += self::sale_money('outsource_settle',$array['id'],$settleWhere);
                $refundMoney = self::sale_money('purchase_refund_order',$array['id'],$saleWhere);
                $purchaseMoney =$purchaseMoney- $refundMoney;
                //实际付款金额
                $payMoney = find(array('table'=>'record','where'=>"typeId = '$array[id]' and direction = '+'".$recWhere,'sum'=>"money"));
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '供应商类别'=>$array['category'],
                            '供应商编码'=>$array['code'],
                            '供应商'=>$array['name'],
                            '期初余额'=>$initMoney,
                            '采购金额'=>round($purchaseMoney,2),
                            '其他应付金额'=>$otherPay,
                            '实际付款金额'=>round($payMoney,2),
                            '应付款金额'=>round($otherPay+$purchaseMoney-$otherIn-$payMoney+$initMoney,2),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = $this->control['name'] . "导出了往来单位一览表";
            $this->logText(["type" => 'currentUnitMxSupplier', "text" => $text]);
            $this->excelOut($title, $data, "往来单位一览表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            '供应商一览表'=>[
                [
                    'columnName'=>'供应商类别',
                    'aliasName'=>'供应商类别',
                ],
                [
                    'columnName'=>'供应商编码',
                    'aliasName'=>'供应商编码',
                ],
                [
                    'columnName'=>'供应商',
                    'aliasName'=>'供应商',
                ],
                [
                    'columnName'=>'期初余额',
                    'aliasName'=>'期初余额(元)',
                ],
                [
                    'columnName'=>'采购金额',
                    'aliasName'=>'采购金额(元)',
                ],
                [
                    'columnName'=>'其他应付金额',
                    'aliasName'=>'其他应付金额(元)',
                ],
                [
                    'columnName'=>'实际付款金额',
                    'aliasName'=>'实际付款金额(元)',
                ],
                [
                    'columnName'=>'应付款金额',
                    'aliasName'=>'应付款金额(元)',
                ],
            ],
            default=>  [
                [
                    'columnName'=>'客户类别',
                    'aliasName'=>'客户类别',
                ],
                [
                    'columnName'=>'客户编码',
                    'aliasName'=>'客户编码',
                ],
                [
                    'columnName'=>'客户',
                    'aliasName'=>'客户',
                ],
                [
                    'columnName'=>'期初余额',
                    'aliasName'=>'期初余额(元)',
                ],
                [
                    'columnName'=>'销售金额',
                    'aliasName'=>'销售金额(元)',
                ],
                [
                    'columnName'=>'其他应收金额',
                    'aliasName'=>'其他应收金额(元)',
                ],
                [
                    'columnName'=>'实际收款金额',
                    'aliasName'=>'实际收款金额(元)',
                ],
                [
                    'columnName'=>'应收款金额',
                    'aliasName'=>'应收款金额(元)',
                ],
            ]
        };
    }
}

